<script lang="ts" setup>
import Menu from "@/components/user/Menu.vue";
import {useRoute, useRouter} from "vue-router";
import {onMounted, reactive, ref, toRefs} from "vue";
import {getUserinfo, updateUserInfo, updateUserPwd} from "@/api/user";
import man from "@/assets/images/man.png";
import {ElMessage, type FormInstance} from "element-plus";
import {useAuthStore} from "@/stores/auth";

const route = useRoute();
const router = useRouter();
const authStore = useAuthStore();
const pwdRef = ref();
const state = reactive({
  isLoading: false,
  isLoading2: false,
  userPhoto: "",
  nickName: "",
  baseUrl: import.meta.env.VITE_APP_BASE_API_URL,
  imgBaseUrl: import.meta.env.VITE_APP_BASE_IMG_URL,
  userSex: 0,
  form: {
    oldPassword: '',
    newPassword: '',
    confirmPassword: ''
  },
  rules: {
    oldPassword: [
      {required: true, message: '密码不能为空', trigger: ['blur', 'submit']},
      {min: 6, max: 20, message: '密码长度需在6到20位之间', trigger: ['blur', 'submit']},
      {
        pattern: /^(?=.*[A-Za-z])(?=.*\d)[A-Za-z\d]{6,20}$/,
        message: '密码必须包含字母和数字',
        trigger: ['blur', 'submit']
      }
    ],
    newPassword: [
      {required: true, message: '密码不能为空', trigger: ['blur', 'submit']},
      {min: 6, max: 20, message: '密码长度需在6到20位之间', trigger: ['blur', 'submit']},
      {
        pattern: /^(?=.*[A-Za-z])(?=.*\d)[A-Za-z\d]{6,20}$/,
        message: '密码必须包含字母和数字',
        trigger: ['blur', 'submit']
      }
    ],
    confirmPassword: [
      {required: true, message: '确认密码不能为空', trigger: ['blur', 'submit']},
      {validator: validatePasswordConfirm, trigger: ['blur', 'submit']}
    ]
  }
});

const {isLoading, isLoading2, userPhoto, nickName, baseUrl, imgBaseUrl, userSex, form, rules} = toRefs(state)

function validatePasswordConfirm(rule: any, value: string, callback: (error?: string) => void) {
  if (value !== state.form.newPassword) {
    callback('两次输入的密码不一致');
  } else {
    callback();
  }
}

onMounted(async () => {
  const {data} = await getUserinfo();
  state.userPhoto = data.userPhoto;
  state.nickName = data.nickName;
  state.userSex = Number(data.userSex);
});

const beforeAvatarUpload = (rawFile: any) => {
  const allowedImageTypes = ['image/jpeg', 'image/png', 'image/gif'];

  // 检查图片格式是否允许
  if (!allowedImageTypes.includes(rawFile.type)) {
    ElMessage.error("必须上传 JPG, PNG 或 GIF 格式的图片!");
    return false;
  }

  // 检查图片大小
  else if (rawFile.size / 1024 / 1024 > 5) {
    ElMessage.error("图片大小最多 5MB!");
    return false;
  }

  return true;
};


const handleAvatarSuccess = (response: any, uploadFile: any) => {
  state.userPhoto = response.data;
  ElMessage.success("头像上传成功!");
}
const saveUserInfo = async () => {
  state.isLoading = true;
  try {
    await updateUserInfo({nickName: state.nickName, userPhoto: state.userPhoto, userSex: state.userSex});
    authStore.setUserPhoto(state.userPhoto)
    ElMessage.success("用户信息修改成功!");
  } catch (e) {

  } finally {
    state.isLoading = false;
  }
}
const handleUpdatePwd = async (formEl: FormInstance | undefined) => {
  if (!formEl) return
  formEl.validate(async (valid) => {
    if (valid) {
      state.isLoading2 = true;
      try {
        await updateUserPwd({oldPassword: state.form.oldPassword, newPassword: state.form.newPassword})
        ElMessage.success("密码修改成功!");
        formEl.resetFields()
      } finally {
        state.isLoading2 = false;
      }
    } else {
      return false;
    }
  })

}

</script>
<template>
  <div class="main">
    <div class="container">
      <div class="left">
        <Menu></Menu>
      </div>
      <div class="right">
        <div class="user-form">
          <el-card>
            <template v-slot:header>
              <div class="clearfix">
                <span>基本资料</span>
              </div>
            </template>
            <el-form>
              <el-form-item label="头像">
                <div class="avatar-uploader">
                  <el-upload
                      :action="baseUrl + '/front/resource/image'"
                      :before-upload="beforeAvatarUpload"
                      :on-success="handleAvatarSuccess"
                      :show-file-list="false"
                  >
                    <img
                        :src="userPhoto ? imgBaseUrl + userPhoto : man"
                        class="avatar"
                    />
                  </el-upload>
                </div>
              </el-form-item>
              <el-form-item label="昵称">
                <el-input v-model="nickName" maxlength="15" placeholder="请输入昵称"></el-input>
              </el-form-item>
              <el-form-item label="性别">
                <el-radio-group v-model="userSex">
                  <el-radio :label="0">男</el-radio>
                  <el-radio :label="1">女</el-radio>
                </el-radio-group>
              </el-form-item>
            </el-form>
            <el-button :loading="isLoading" type="primary" @click="saveUserInfo">保存</el-button>
          </el-card>
        </div>
        <div class="user-pwd">
          <el-card>
            <template v-slot:header>
              <div class="clearfix">
                <span>密码修改</span>
              </div>
            </template>
            <el-form ref="pwdRef" :model="form" :rules="rules" label-width="80">
              <el-form-item label="旧密码" prop="oldPassword">
                <el-input v-model="form.oldPassword" placeholder="请输入旧密码"
                          show-password type="password"/>
              </el-form-item>
              <el-form-item label="新密码" prop="newPassword">
                <el-input v-model="form.newPassword" placeholder="请输入新密码"
                          show-password type="password"/>
              </el-form-item>
              <el-form-item label="确认密码" prop="confirmPassword">
                <el-input v-model="form.confirmPassword" placeholder="请确认密码"
                          show-password type="password"/>
              </el-form-item>
              <el-form-item>
                <el-button :loading="isLoading2" type="primary" @click="handleUpdatePwd(pwdRef)">保存</el-button>
              </el-form-item>
            </el-form>
          </el-card>
        </div>
      </div>
    </div>
  </div>
</template>
<style lang="scss" scoped>
.main {
  background-color: #F5F5F5;
  display: flex;
  justify-content: center;
  user-select: none;

  .container {
    width: 60%;
    background-color: #fff;
    display: flex;
    box-sizing: border-box;
    min-height: 82vh;

    .left {
      width: 20%;
      box-sizing: border-box;
      flex: 1;
      border-right: 1px solid #F5F5F5;
      padding: 10px 0;
    }

    .right {
      //border: 1px solid #000;
      flex: 3;
      padding: 10px;
      display: flex;
      gap: 30px;
      box-sizing: border-box;
      height: 400px;

      .user-form {
        padding-left: 20px;
        width: 30%;

        .el-card {
          box-sizing: border-box;
          display: flex;
          flex-direction: column;
          height: 100%;

          .avatar-uploader {
            img {
              width: 100px;
              height: 100px;
              border-radius: 50%;
              object-fit: cover;
            }
          }

          .el-button {
            width: 100%;
          }
        }
      }

      .user-pwd {
        //width: 60%;
        .el-card {
          box-sizing: border-box;
          display: flex;
          height: 100%;
          flex-direction: column;
        }
      }
    }
  }
}
</style>